﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using GameDb.Entities;
using GameDb.EF;
using System.Web.Management;
using GameDb.Membership.Code;

namespace GameDb
{
    public class GameDbContext : DbContext
    {
        public DbSet<Game> Games { get; set; }
        public DbSet<GameMatch> GameMatches { get; set; }
        public DbSet<MatchPlayer> MatchPlayers { get; set; }
        public DbSet<MatchPiece> MatchPieces { get; set; }
        public DbSet<PreMatch> PreMatches { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<MatchTurn> MatchTurns { get; set; }
        public DbSet<MatchPlayerTurn> MatchPlayerTurns { get; set; }
        public DbSet<MatchPlayerTurnPiece> MatchPlayerTurnPieces { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<System.Data.Entity.Infrastructure.IncludeMetadataConvention>();
        }
    }

    public class GameDbContextInitializer
    {
        public static void Init()
        {
            //Database.SetInitializer<GameDbContext>(new GameDropCreateDatabaseIfModelChanges());
            //using (var db = new GameDbContext())
            //{
            //    db.Database.Initialize(false);
            //}
        }
    }


    public class GameDropCreateDatabaseIfModelChanges : DropCreateDatabaseIfModelChanges<GameDbContext>
    {
        protected override void Seed(GameDbContext context)
        {
            context.Database.ExecuteSqlCommand("create user [IIS AppPool\\cellblock-d] from login [IIS AppPool\\cellblock-d]");
            context.Database.ExecuteSqlCommand("sp_addrolemember 'db_owner', [IIS AppPool\\cellblock-d]");
            CreateSeedMember("admin");
            CreateSeedMember("amy");
            CreateSeedMember("scott");
            CreateSeedMember("mikey");
            CreateSeedMember("david", "222222");
            CreateSeedMember("gaines", "333333");
        }

        private void CreateSeedMember(string userName)
        {
            CreateSeedMember(userName, "111111");
        }

        private void CreateSeedMember(string userName, string password)
        {
            CodeFirstSecurity.CreateAccount(userName, password, userName + "@demo.com");
        }

    }
}
